import { toSuccess, useEntityManager } from "@sker/core"
import { KsAccount, KsLiveRoom, KsRedPacket } from "@sker/entities"
import { useData } from "@sker/runtime"
import dayjs from "dayjs"
import { z } from "zod"


export default async () => {
    const input = z.object({
        type: z.optional(z.string()),
        start: z.string(),
        end: z.string()
    })
    const body = input.parse(useData())
    body.type = body.type || '口令';
    let start = dayjs().set('hour', parseInt(body.start)).subtract(8, 'hour').hour()
    let end = dayjs().set('hour', parseInt(body.end)).subtract(8, 'hour').hour()


    const list = await useEntityManager(async m => {
        const list = await m.createQueryBuilder()
            .select('account.user_id', 'user_id')
            .from(KsLiveRoom, 'room')
            .leftJoin(KsRedPacket, 'red', 'red.room_id=room.id')
            .leftJoin(KsAccount, 'account', 'account.user_id=room.user_id')
            .where(`date_part('hour',room.open_time)>=:start and date_part('hour',room.open_time)<=:end`, { start: start, end: end })
            .andWhere('red.type=:type', { type: body.type })
            .groupBy('account.user_id')
            .orderBy('random()')
            .limit(100)
            .execute()
        return list.map(item => {
            item.link = `kwai://live/play/~${item.user_id}`
            return item;
        })
        // return list;
    })

    return toSuccess(list, list.count)

}